<?php


class Mod {
    public $uid;
    public $username;

    public static $config = array();

    public function log($data) {
        $data['uid'] = $this->uid;
        $data['username'] = $this->username;
        db()->feed->insert($data);
    }

	public static function start() {
		$params = explode('/', trim($_SERVER['PATH_INFO'], '/'));
		foreach ($params as $p) {
			list($key, $val) = explode(':', $p);
			$_GET += array($key => $val);
			$_REQUEST += $_GET;
		}

		list($mod, $act) = explode(':', $params[0]);
		require "act/{$mod}.php";
		$mod = 'Mod_'.$mod;
		$mod = new $mod();
		$mod->uid = '1';
		$mod->username = 'Jayce';
		$mod->$act();
	}
}

/**
 * 从一个数组里抽出指定键名的项
 * 如：
 * $arr = array('a' => 1, 'b' => '2', 'c' => 3);
 * $pick_arr = array_pick($arr, 'a', 'b');
 * $pick_arr 的值为 array('a' => 1, 'b' => 2);
 *
 * @return array
 */
function array_pick($arr, $key) {
	$args = func_get_args();
	$input = array_shift($args);
    $pick_arr = array();
    foreach ($args as $k) {
        $pick_arr[$k] = $input[$k];
    }
    return $pick_arr;
}

function tpl($file, $data = array()) {
    extract($data);
    include "tpl/head.php";
    include "tpl/{$file}.php";
    include "tpl/foot.php";
}

function db() {
    $conn = new Mongo();
    $db = Mod::$config['db']['name'];
    return $conn->$db;
}

function feed_parse($data) {
    $arr = array(
        'default:addObj' => '{:username}添加了<a href="'. url('default:showObj') .'?name={:name}">{:name}</a>'
    );
    $str = $arr[$data['act']];
    foreach ($data as $k => $v) {
        $str = str_replace("{:$k}", $v, $str);
    }
    return $str;
}

function url($url) {
    return "/index.php/".$url;
}

function msg($msg, $args=array()) {
    if (!empty($args['url'])) {
        header('location:'.$args['url']);
    }
    tpl("msg", array('msg' => $msg));
}